#include <avr/io.h>
#include <avr/iom164.h> 
#include <avr/interrupt.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define CONTROL 	0x9F
#define CHARACTER	0xFE

//#include "WProgram.h"
//#include "SerialLCD.h"
//#include "NewSoftSerial.h"

void power_on ();
void get_data();
void serial_init();
void lcd_transmit(unsigned char data);
char lcd_receive();
void lcd_flush();
void obd_transmit(unsigned char data);
char obd_receive();
int main(void){
	serial_init(); // Initialize Serial
	power_on(); // Turn Power Light On

	while(1){
		get_data();
	}		
} 

void power_on (){
	DDRA=0xff;
	DDRD=0xff;
	PORTA = 0x01;
}

void get_data (){
	int flag = 0;
	unsigned char data, data1;
	PORTA = 0x01;
	data = lcd_receive();	
	if (data == 0xA3){
		lcd_transmit(0x9F);
		PORTA = 0x02;
		lcd_transmit(0x83);
		PORTA = 0x03;
		lcd_transmit(0xA5);
		PORTA = 0x04;
		data = lcd_receive();
		PORTA = 0x05;
		if (data == 0xAA){

			// Turn on Backlight

			lcd_transmit(CONTROL);
			lcd_transmit(0x81);
		
			// LCD On

			lcd_transmit(CONTROL);
			lcd_transmit(0x83);

			// LCD Clear
			
			lcd_transmit(CONTROL);
			lcd_transmit(0x65);

			// Display On
	
			lcd_transmit(CONTROL);
			lcd_transmit(0x64);

			// Return Home

			lcd_transmit(CONTROL);
			lcd_transmit(0x61);
			
			// Cursor On

			lcd_transmit(CONTROL);
			lcd_transmit(0x67);

			// Blink On

			lcd_transmit(CONTROL);
			lcd_transmit(0x69);
			
			lcd_transmit(CONTROL);
			lcd_transmit(0x71);
	
			// Left to right

			lcd_transmit(CONTROL);
			lcd_transmit(0x70);

			// Autoscroll
			
			lcd_transmit(CONTROL);
			lcd_transmit(0x6D);

			lcd_transmit(CONTROL);
			lcd_transmit(0x6C);
			// Set cursor

			/*lcd_transmit(CONTROL);
			lcd_transmit(0xFF);
			PORTA = 0x06;
			while( (data = lcd_receive()) != 0x5A);
			int i;
			for(i=0;i<10000;i++){}
			lcd_transmit(0x80);
			lcd_transmit(0x00);
						
			// Set cursor again

/*			lcd_transmit(CONTROL);
			lcd_transmit(0xFF);
			while( (data = lcd_receive()) != 0x5B);
			lcd_transmit(0x80);
			lcd_transmit(0x00);*/

			lcd_transmit(CHARACTER);
			while(1){
				lcd_transmit(0x23);
				PORTA = 0x07;
			} 
			
			PORTA = 0x07;
			while(1);
		}
	}	 
}
void serial_init(){

//	PRR0 |= (0<<PRUSART1)|(0<<PRUSART0); // Power Reduction Off

	UCSR0A |= (1<<U2X0);
	UCSR0B |= (1<<RXEN0)|(1<<TXEN0);
	UCSR0C |= (1<<USBS0)|(3<<UCSZ00);
	UBRR0H = 0;
	UBRR0L = 12;


	UCSR1A |= (1<<U2X1);
	UCSR1B |= (1<<RXEN1)|(1<<TXEN1); // Allow transmit and receive
	UCSR1C |= (1<<USBS1)|(3<<UCSZ10); // 8 Bit 2 Stop Bits
	UBRR1H = 0;
	UBRR1L = 12; // 9600 Baud
}

void lcd_transmit (unsigned char data){
	while( !(UCSR1A & (1<<UDRE1)));
	UDR1 = data;
}

char lcd_receive (void){
	while (!(UCSR1A & (1<<RXC1)));
	return UDR1;
}	

void obd_transmit (unsigned char data){
	while( !(UCSR0A & (1<<UDRE0)));
	UDR0 = data;
}

char obd_receive (void){
	while (!(UCSR0A & (1<<RXC0)));
	return UDR0;
}

void lcd_flush (void){
	char tmp;
	while (UCSR1A & (1<<RXC1) ) tmp = UDR1;
}
